package com.gobang.common.exception;

import com.gobang.domain.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;


import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 统一处理系统中的各种异常，返回标准格式的错误响应
 * 
 * @author System
 * @since 1.0.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义业务异常
     *
     * @param ex 业务异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleBaseException(BaseException ex, HttpServletRequest request) {
        logger.warn("业务异常: {}, 请求路径: {}", ex.getMessage(), request.getRequestURI(), ex);
        return Result.error(ex.getCode(), ex.getMessage()).withPath(request.getRequestURI());
    }

    /**
     * 处理参数校验异常 - @RequestBody 参数校验
     *
     * @param ex 参数校验异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
        BindingResult bindingResult = ex.getBindingResult();
        List<String> errors = bindingResult.getFieldErrors()
                .stream()
                .map(this::formatFieldError)
                .collect(Collectors.toList());
        
        String errorMessage = String.join("; ", errors);
        logger.warn("参数校验失败: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_VALIDATE_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理参数绑定异常 - @ModelAttribute 参数校验
     *
     * @param ex 参数绑定异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleBindException(BindException ex, HttpServletRequest request) {
        List<String> errors = ex.getFieldErrors()
                .stream()
                .map(this::formatFieldError)
                .collect(Collectors.toList());
        
        String errorMessage = String.join("; ", errors);
        logger.warn("参数绑定异常: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_VALIDATE_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理约束违反异常 - @RequestParam 参数校验
     *
     * @param ex 约束违反异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleConstraintViolationException(ConstraintViolationException ex, HttpServletRequest request) {
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        List<String> errors = violations.stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .collect(Collectors.toList());
        
        String errorMessage = String.join("; ", errors);
        logger.warn("约束违反异常: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_VALIDATE_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理缺少请求参数异常
     *
     * @param ex 缺少请求参数异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex, HttpServletRequest request) {
        String errorMessage = String.format("缺少必需的请求参数: %s", ex.getParameterName());
        logger.warn("缺少请求参数: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理参数类型不匹配异常
     *
     * @param ex 参数类型不匹配异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex, HttpServletRequest request) {
        String errorMessage = String.format("参数类型错误: %s，期望类型: %s", 
                ex.getName(), ex.getRequiredType() != null ? ex.getRequiredType().getSimpleName() : "未知");
        logger.warn("参数类型不匹配: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理HTTP消息不可读异常（JSON格式错误等）
     *
     * @param ex HTTP消息不可读异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex, HttpServletRequest request) {
        String errorMessage = "请求体格式错误，请检查JSON格式";
        logger.warn("HTTP消息不可读: {}, 请求路径: {}", ex.getMessage(), request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理HTTP请求方法不支持异常
     *
     * @param ex HTTP请求方法不支持异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result<Object> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex, HttpServletRequest request) {
        String errorMessage = String.format("不支持的请求方法: %s", ex.getMethod());
        logger.warn("HTTP请求方法不支持: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.PARAM_ERROR, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理404异常
     *
     * @param ex 404异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpServletRequest request) {
        String errorMessage = String.format("请求的资源不存在: %s", ex.getRequestURL());
        logger.warn("404异常: {}, 请求路径: {}", errorMessage, request.getRequestURI());
        
        return Result.error(ErrorCode.DATA_NOT_FOUND, errorMessage).withPath(request.getRequestURI());
    }

    /**
     * 处理空指针异常
     *
     * @param ex 空指针异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleNullPointerException(NullPointerException ex, HttpServletRequest request) {
        logger.error("空指针异常, 请求路径: {}", request.getRequestURI(), ex);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统内部错误").withPath(request.getRequestURI());
    }

    /**
     * 处理运行时异常
     *
     * @param ex 运行时异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleRuntimeException(RuntimeException ex, HttpServletRequest request) {
        logger.error("运行时异常, 请求路径: {}", request.getRequestURI(), ex);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统内部错误").withPath(request.getRequestURI());
    }

    /**
     * 处理其他未捕获异常
     *
     * @param ex 未知异常
     * @param request HTTP请求
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleException(Exception ex, HttpServletRequest request) {
        logger.error("未知异常, 请求路径: {}", request.getRequestURI(), ex);
        return Result.error(ErrorCode.SYSTEM_ERROR, "系统内部错误").withPath(request.getRequestURI());
    }

    /**
     * 格式化字段错误信息
     *
     * @param fieldError 字段错误
     * @return 格式化后的错误信息
     */
    private String formatFieldError(FieldError fieldError) {
        return String.format("%s: %s", fieldError.getField(), fieldError.getDefaultMessage());
    }
} 